package com.guxingke.gblog.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.guxingke.gblog.dmo.Category;
import com.guxingke.gblog.dto.CategoryDto;
import com.guxingke.gblog.service.CategoryService;
import com.guxingke.gblog.service.impl.CategoryServiceImpl;
import com.guxingke.gblog.util.StringUtil;
import com.opensymphony.xwork2.ActionSupport;

public class CategoryManageAction extends ActionSupport implements
		ServletRequestAware {
	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	private CategoryService categoryService = new CategoryServiceImpl();
	List<CategoryDto> categories;
	String mainPage;
	Category category;
	String error;

	@Override
	public String execute() throws Exception {
		categories = categoryService.getCategories();
		mainPage = "template/category/manage-list.jsp";
		return SUCCESS;
	}

	public String preSave() throws Exception {
		String categoryId = request.getParameter("categoryId");
		if (StringUtil.isNotEmpty(categoryId)) {
			category = categoryService
					.getCategory(Integer.parseInt(categoryId));
		}
		mainPage = "template/category/manage-save.jsp";
		return SUCCESS;
	}

	public String save() throws Exception {
		String categoryId = request.getParameter("categoryId");

		if (StringUtil.isNotEmpty(categoryId)) {
			categoryService.updateCategory(category);
		} else {
			categoryService.saveCategory(category);
		}

		return "otherSuccess";
	}

	public String delete() throws Exception {
		String categoryId = request.getParameter("categoryId");
		if (categoryService.exist(Integer.parseInt(categoryId))) {
			request.setAttribute("error", "此分类下尚有博文，不可删除");
		} else {
			categoryService.deleteCategory(Integer.parseInt(categoryId));
		}
		return "otherSuccess";
	}

	public List<CategoryDto> getCategories() {
		return categories;
	}

	public void setCategories(List<CategoryDto> categories) {
		this.categories = categories;
	}

	public String getMainPage() {
		return mainPage;
	}

	public void setMainPage(String mainPage) {
		this.mainPage = mainPage;
	}

	public Category getCategory() {
		return category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
}
